package com.weasing.res.web.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.weasing.res.domain.WxAdmin;
import com.weasing.res.domain.WxRole;
import com.weasing.res.service.IWxAdminService;
import com.weasing.res.service.IWxDictService;
import com.weasing.res.service.IWxRoleService;
import com.weasing.res.service.IWxUserdetailService;
import com.weasing.res.service.IWxUserlistService;
import com.weasing.res.utils.DicUtils;
import com.weasing.res.utils.MD5Utils;
import com.weasing.res.utils.RESUtils;
import com.weasing.res.utils.StringUtil;
import com.weasing.res.web.action.base.BaseAction;

import net.sf.json.JSONArray;

/**
 * res系统的监控方法
 * 
 * @author 黄龙
 *
 */
@Controller
@Scope("prototype")
public class WxAdminAction extends BaseAction<WxAdmin> {
	@Autowired
	private IWxAdminService wxAdminService;
	@Autowired
	private IWxRoleService wxRoleService;
	@Autowired
	private IWxUserdetailService wxUserdetailService;
	@Autowired
	private IWxUserlistService wxUserlistService;
	@Autowired
	private IWxDictService wxDictService;

	private String checkUsername;
	private String newPassword;
	private String alignPassword;
	private Log logger = LogFactory.getLog(this.getClass());

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public void setAlignPassword(String alignPassword) {
		this.alignPassword = alignPassword;
	}

	public void setCheckUsername(String checkUsername) {
		this.checkUsername = checkUsername;
	}
	/**
	 * 用户登录,使用shiro框架提供的方式进行认证操作
	 * 
	 * @author 黄龙
	 */
	public String login() {
		MDC.put("optype", 5);// 操作内容说明 1 创建 2修改 3修改状态 4删除记录5登陆
		Subject subject = SecurityUtils.getSubject();// 获得当前用户对象,状态为“未认证”
		AuthenticationToken token = new UsernamePasswordToken(
				model.getUsername(),
				MD5Utils.md5Double(model.getPassword()));// 创建用户名密码令牌对象
		try {
			subject.login(token);
		} catch (Exception e) {
			// 登录失败的前台标示
			RESUtils.print("0");
			// this.addActionError("输入的账号或者密码错误");
			return null;
		}
		// 从对象里面取出wxAdmin 存到session
		RESUtils.print("1");
		WxAdmin wxAdmin = (WxAdmin) subject.getPrincipal();
		WxRole role = wxRoleService.findById(wxAdmin.getRoleid());
		RESUtils.getSession().setAttribute("wxAdmin", wxAdmin);
		RESUtils.getSession().setAttribute("role", role);
		logger.info(role.getRolename() + "-" + wxAdmin.getTruename() + "-登录");// 操作内容说明
		return null;
	}

	/**
	 * 注销用户
	 * 
	 * @return
	 */
	public String logout() {
		logger.info("管理员注销");// 操作内容说明
		MDC.put("optype", 0);// 操作内容说明 1 创建 2修改 3修改状态 4删除记录5登陆
		HttpSession session = ServletActionContext.getRequest().getSession();
		session.invalidate();
		// System.out.println("进入注销方法");
		return LOGIN;
	}

	/**
	 * ajax请求修改密码
	 * 
	 * @return
	 * @throws IOException
	 */
	public String editPasswordForm() throws IOException {
		logger.info("管理员修改密码");// 操作内容说明
		MDC.put("optype", 2);// 操作内容说明 1 创建 2修改 3修改状态 4删除记录5登陆
		WxAdmin wxAdmin = RESUtils.getLoginWxAdmin();
		String flag = "0";// 0 失败 1成功 2密码输入错误
		try {
		// 判断密码正确与否
		if (!wxAdmin.getPassword()
				.equals(MD5Utils.md5Double(model.getPassword()))) {
			flag = "2"; // 当前密码和用户密码不一致
			} else {

			if (StringUtil.isNotNulls(newPassword, alignPassword)
					&& newPassword.equals(alignPassword)) {
				// 执行修改密码
					wxAdmin.setPassword(
							MD5Utils.md5Double(newPassword));
					wxAdminService.update(wxAdmin);
					// 刷新session
					RESUtils.getSession().setAttribute("wxAdmin", wxAdmin);
				flag = "1";
			}
			}
		} catch (Exception ex) {
			flag = "0";
			ex.printStackTrace();
		}
		ServletActionContext.getResponse().getWriter().print(flag);

		return NONE;
	}

	/**
	 * ajax请求个人信息
	 * 
	 * @author 黄龙
	 * @return
	 * @throws IOException
	 */
	public String editInfoForm() throws IOException {
		logger.info("管理员修改个人信息");// 操作内容说明
		MDC.put("optype", 2);// 操作内容说明 1 创建 2修改 3修改状态 4删除记录5登陆
		WxAdmin wxAdmin = RESUtils.getLoginWxAdmin();
		String flag = "0";// 0 失败 1成功
		try {
			if (null != model){
				// 执行修改个人信息
				if (StringUtil.isNotNulls(model.getTruename()))
					wxAdmin.setTruename(model.getTruename());
				if (StringUtil.isNotNulls(model.getExcardno()))
					wxAdmin.setExcardno(model.getExcardno());
				if (StringUtil.isNotNulls(model.getCompname()))
					wxAdmin.setCompname(model.getCompname());
				if (StringUtil.isNotNulls(model.getCompshortname()))
					wxAdmin.setCompshortname(model.getCompshortname());
					wxAdminService.update(wxAdmin);
					// 刷新session
					RESUtils.getSession().setAttribute("wxAdmin", wxAdmin);
				flag = "1";
			}
		} catch (Exception ex) {
			flag = "0";
			ex.printStackTrace();
		}
		ServletActionContext.getResponse().getWriter().print(flag);

		return NONE;
	}

	/**
	 * ajax请求修改提示问题
	 * 
	 * @author 黄龙
	 * @return
	 * @throws IOException
	 */
	public String editQuesForm() throws IOException {
		logger.info("管理员修改提示问题");// 操作内容说明
		MDC.put("optype", 2);// 操作内容说明 1 创建 2修改 3修改状态 4删除记录5登陆
		System.out.println(111);
		WxAdmin wxAdmin = RESUtils.getLoginWxAdmin();
		String flag = "0";// 0 失败 1成功
		try {
			if (null != model) {
				// 执行修改个人信息
				wxAdmin.setFindpassques1(
						Integer.valueOf(model.getFindpassques1()));
				;
				wxAdmin.setFindpassques2(
						Integer.valueOf(model.getFindpassques2()));
				;
				if (StringUtil.isNotNulls(model.getFindpassans1()))
					wxAdmin.setFindpassans1(model.getFindpassans1());
				if (StringUtil.isNotNulls(model.getFindpassans2()))
					wxAdmin.setFindpassans2(model.getFindpassans2());
				wxAdminService.update(wxAdmin);
				// 刷新session
				RESUtils.getSession().setAttribute("wxAdmin", wxAdmin);
				flag = "1";
			}
		} catch (Exception ex) {
			flag = "0";
			ex.printStackTrace();
		}
		ServletActionContext.getResponse().getWriter().print(flag);

		return NONE;
	}

	/**
	 * 注册用户
	 * 
	 * @author 黄龙
	 */
	public String register() {
		logger.info("注册管理员");// 操作内容说明
		MDC.put("optype", 0);// 操作内容说明 1 创建 2修改 3修改状态 4删除记录5登陆
		WxAdmin wxAdmin = (WxAdmin) model;
		// 组装wxAdmin
		if (StringUtil.isNotNulls(model.getUsername(), model.getPassword())) {
			// 判断用户名可不可以使用
			wxAdmin.setCreatetime(new Timestamp(System.currentTimeMillis()));
			if (wxAdminService.checkUserName(model.getUsername())) {
				try {
					wxAdmin.setRoleid(3);
					wxAdminService.register(wxAdmin);
					// 默认权限数据 游客
					RESUtils.print("1");// 0注册失败,1 注册成功
				} catch (Exception ex) {
					RESUtils.print("0");
					this.addActionError("注册失败");
				}
			}
		}
		return null;
	}

	/**
	 * 异步验证请求 验证重复用户名
	 * 
	 * @throws IOException
	 */
	public void checkUserName() throws IOException {
		WxAdmin wxAdmin = (WxAdmin) model;
		String flag = "1"; // 标志 0代表可以用 1代表重复不可用
		if (null != wxAdmin.getUsername()) {
			if (wxAdminService.checkUserName(wxAdmin.getUsername())) {
				flag = "0";
			}
		}
		ServletActionContext.getResponse().getWriter().print(flag);
	}

	/**
	 * 异步验证请求 验证重复用户名
	 * 
	 * @throws IOException
	 */
	public void checkUserByName() throws IOException {
		String flag = "1"; // 标志 0代表可以用 1代表重复不可用
		if (null != checkUsername) {
			if (wxAdminService.checkUserName(checkUsername)) {
				flag = "0";
			}
		}
		ServletActionContext.getResponse().getWriter().print(flag);
	}
	/**
	 * 删除用户
	 * 
	 */
	@RequiresPermissions("role-delete")
	public void deleteWxAdmin() {
		try {
			wxAdminService.delete(model);
			RESUtils.print("1");
		} catch (Exception e) {
			e.printStackTrace();
			RESUtils.print("0");

		}
	}

	/**
	 * 更新用户 更新用户--及其角色
	 * 
	 * @author 黄龙
	 */
	public void updateWxAdmin() {
		try {
			WxAdmin wxAdmin = wxAdminService.findById(model.getId());
			wxAdmin.setRoleid(model.getRoleid());
			wxAdminService.update(wxAdmin);
			RESUtils.print("1");
		} catch (Exception e) {
			RESUtils.print("0");
			e.printStackTrace();
		}
	}
	
	/**
	 * 首页 findUserAndDetail 获得犯罪嫌疑人总数 和评估次数
	 * 
	 * 
	 * @author 黄龙
	 */
	public String findUserAndDetail() {
		Integer userdetailCount = wxUserdetailService.findCount();
		Integer userlistCount = wxUserlistService.findCount();
		RESUtils.getSession().setAttribute("userdetailCount",
				userdetailCount);
		RESUtils.getSession().setAttribute("userlistCount", userlistCount);
		return "home";
	}

	/**
	 * 分页查询所有角色的属性
	 * 
	 * @return
	 */
	// @RequiresPermissions("role-list")
	public String findAll() {
		// pageBean.setCurrentPage(currentPage);
		String currentPageStr = RESUtils.getRequest()
				.getParameter("currentPage");
		if (null != currentPageStr) {
		int currentPage = Integer.valueOf(currentPageStr);
		pageBean.setCurrentPage(currentPage);
		}
		wxAdminService.pageQuery(pageBean);
		List<WxAdmin> rows = pageBean.getRows();
		for (WxAdmin wxAdmin : rows) {
			WxRole wxRole = wxRoleService.findById(wxAdmin.getRoleid());
			wxAdmin.setWxRole(wxRole);
		}
		// List<WxAdmin> rows = wxAdminService.findAllAndRole();
		List<WxRole> findAllrole = wxRoleService.findAll();
		RESUtils.getRequest().setAttribute("wxAdminList", rows);
		RESUtils.getRequest().setAttribute("wxWxRoleList", findAllrole);
		RESUtils.getRequest().setAttribute("pageBean", pageBean);
		// ValueStack valueStack = ActionContext.getContext().getValueStack();
		// 存入值
		// valueStack.push(findAllAndRole);
		return "wxRolelist";
	}

	/**
	 * 获得密码提示问题
	 * 
	 */
	public void findDicQues() {
		String dictName = wxDictService.findWxDictByDictName("findpassques1");
		List<String> string2List = DicUtils.string2List(dictName);
		JSONArray fromObject = JSONArray.fromObject(string2List);
		// System.out.println(fromObject.toString());
		RESUtils.printJSON(fromObject.toString());
	}

	/**
	 * 管理员界面跳转方法
	 * 
	 * jsp/info.jsp
	 * 
	 */
	public String info() {
		return "info";
	}
}
